/**
 * @Description:处理mescroll分页 适配后台pageQuery
 * @param {Object} page
 * @param {number} page.num 当前页
 * @param {number} page.size 一页多少条数据
 */
export function transformPagination(page) {
    return {
        start: (page.num - 1) * page.size,
        limit: page.size
    }
}


/**
 * 获取页面栈
 * @param {number} num=2获取上一页面
 * **/
export function getCurrentPage(num = 2) {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - num];
    return new Promise((resolve, reject) => {
        if (currentPage) {
            resolve(currentPage);
        } else {
            reject("页面不存在");
        }
    });
}

/**
 * @Description: 支付
 * @param res
 * @returns {Promise<unknown>}
 */
export function requestPayment(res) {
    const promise = new Promise((resolve, reject) => {
        uni.requestPayment({
            ...res,
            success: res => {
                resolve(res);
            },
            fail: err => {
                reject(err);
            }
        })
    })
    return promise
}

/** 处理富文本图片 不是全路径*/
export function addMaxWidthStyleToImages(html, bool = false) {
    const baseUrl = process.env.VUE_APP_URL;
    const imgUrl = process.env.VUE_APP_IMG_VIEW;
    const newHtml = html.replace(/<img([^>]+)>/gi, (match, attrs) => {
        let processedAttrs = attrs.replace(
            /src=(['"])([^'"?]*[?&]id=([^&'"]*))([^'"]*)\1/gi,
            (full, quote, _path, id, rest) => {
                const newSrc = id ? `${baseUrl}${imgUrl}/${id}` : ''
                return newSrc ? `src=${quote}${newSrc}${quote}` : full
            }
        );
        return `<img ${processedAttrs}>`;
    });
    return newHtml;
}
